package me.zhengjie.config;

import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * Flyway 数据库迁移配置
 * 
 * @author zhengjie
 * @date 2024-01-01
 */
@Configuration
public class FlywayConfig {

    @Autowired
    private DataSource dataSource;

    /**
     * 自定义 Flyway 迁移策略
     */
    @Bean
    public FlywayMigrationStrategy flywayMigrationStrategy() {
        return flyway -> {
            // 创建 Flyway 实例
            Flyway flywayInstance = Flyway.configure()
                    .dataSource(dataSource)
                    .encoding("UTF-8")
                    .locations("classpath:db/migration")
                    .sqlMigrationPrefix("V")
                    .sqlMigrationSeparator("__")
                    .sqlMigrationSuffixes(".sql")
                    .validateOnMigrate(true)
                    .baselineOnMigrate(true)
                    .baselineVersion("1")
                    .mixed(false)
                    .load();

            // 执行迁移
            flywayInstance.migrate();
        };
    }
} 